package test.server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class SearchQuery implements Comparable<SearchQuery> {
	private String query = "";

	private Date date = new Date();

	public SearchQuery(String query, Date date) {
		this.query = query;
		this.date = date;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public void createOrUpdateQuery() {
		Iterable<Entity> exisitingList = SearchQueryUtil.getAllQueries();
		List<SearchQuery> entityList = new ArrayList<SearchQuery>();
		int count = 0;
		if (exisitingList != null) {
			for (Entity entity : exisitingList) {
				Date dateTemp = (Date) entity.getProperty("date");
				String queryTemp = (String) entity.getProperty("query");
				entityList.add(new SearchQuery(queryTemp, dateTemp));
				count++;
			}
		}

		if (count < 10) {
			Entity entity = getQuery(query);
			if (entity == null) {
				entity = new Entity("SearchQuery", query);
				entity.setProperty("query", query);
				entity.setProperty("date", date);
			} else {
				entity.setProperty("date", date);
			}
			Util.persistEntity(entity);
		} else {
			Collections.sort(entityList);
			String q = entityList.get(0).query;
			Entity entity = getQuery(q);
			entity.setProperty("date", date);
			entity.setProperty("query", query);
			Util.persistEntity(entity);
		}
	}

	public Entity getQuery(String name) {
		Key key = KeyFactory.createKey("SearchQuery", name);
		return Util.findEntity(key);
	}

	public String toHTML() {
		StringBuffer result = new StringBuffer();
		result.append(query);
		result.append(" at ");
		result.append(date.toLocaleString());
		result.append("<p>");
		return result.toString();
	}

	public Date getDateTime() {
		return date;
	}

	@Override
	public int compareTo(SearchQuery arg0) {
		Date a = this.getDateTime();
		Date b = arg0.getDateTime();
		if (a.before(b))
			return -1;
		else if (a.after(b)) // it's equals
			return 1;
		else
			return 0;
	}

}
